# -*- coding: utf-8 -*-

import os
import logging
import simplejson as json
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

READ_URL = r'https://readitlaterlist.com/v2/get?username=%s&password=%s&apikey=194gFhc2pi8e0VV05fTF16cF98Afp7bO&state=%s'
BOOK_MARK_TEMPLATE = '''
<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<!-- This is an automatically generated file.
It will be read and overwritten.
Do Not Edit! -->
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
%s
</DL><p><!-- Read it later exporter generated. http://rilexporter.appspot.com/ -->
'''

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, {}))

class Exporter(webapp.RequestHandler):
  def post(self):
    username = self.request.get('user')
    password = self.request.get('pw')
    state    = self.request.get('state')

    if self.request.get('submit') == "Export":
      self.response.headers['Content-Type'] = 'application/html'
      self.response.headers['Content-Disposition'] = 'filename=bookmarks.html'

    logging.info(READ_URL % (username, password, state))
    _resp = urlfetch.fetch(READ_URL % (username, password, state))
    _h = json.loads(_resp.content)

    dts = []
    if _h.has_key("list"):
      for item_id, item in _h["list"].items():
        if item.has_key("tags"):
          tags = item["tags"]
        else:
          tags = ""
        dts.append('<DT><A HREF="%s" ADD_DATE="%s" PRIVATE="0" TAGS="%s">%s</A>' % \
            (item["url"], item["time_added"], tags, item["title"]))
    bookmark =  BOOK_MARK_TEMPLATE % ("\n".join(dts))
    self.response.out.write(bookmark)

application = webapp.WSGIApplication([  ('/',MainPage),
                                        ('/export', Exporter),
                                     ], debug = True)
def main():
  run_wsgi_app(application)
if __name__ == "__main__":
  main()
